<?php
/**
 * Created by PhpStorm.
 * User: fuyu
 * Date: 2018/6/25
 * Time: 下午5:30
 */

namespace App\Logic;

use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\RichText\RichText;


/**
 * 万里牛导出
 * Class WlnExport
 * @package App\Logic
 */
class WlnExport extends BaseExport
{

    protected $sourceName = '万里牛';

    protected function setSourceTitle()
    {
        $this->sourceTitle = ["订单编号", "一条SKU", "供应商SKU", "商品名称", "规格", "定制信息", "最晚发货时间", "促销描述", "是否赠品", "数量", "单价", "总价", "收货人", "省", "市", "收货地址", "电话", "支付时间", "外部备注", "支付人姓名", "支付人身份证", "支付流水", "支付单号", "支付方式", "发票抬头", "运单号", "物流公司"];
    }


    protected function setTargetTitle()
    {
        $this->targetTitle = ["订单号", "<必填>下单时间", "付款时间", "交易类型", "备注", "买家留言", "总金额", "运费", "<必填>实付总额", "<必填>收货人姓名", "手机", "固话", "<必填>地址", "邮编", "电子邮箱", "<必填>商品编码", "<必填>商品名称", "规格名称", "<必填>数量", "<必填>单价", "<必填>实付"];
    }

    protected function loadData()
    {
        $worksheet = $this->workbook->getActiveSheet();
        $rowIdx = 0;
        foreach ($worksheet->getRowIterator() as $row) {
            $columnIdx = 0;
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false);

            foreach ($cellIterator as $cell) {
                $value = $cell->getValue();
                if ($value instanceof RichText) {
                    $value = $value->getPlainText();
                }
                $this->sourceData[$rowIdx][$columnIdx] = $value;
                $columnIdx++;
            }
            $rowIdx++;
        }
    }

    protected function transferData()
    {
        $temp = [];
        $productCodes = [];
        $exportData = [];
        $exportData[] = $this->targetTitle;
        foreach ($this->sourceData as $key => $row) {
            if ($key == 0) {
                continue;
            }
            //将相同手机号的数据放在一起
            $orderNo = $row[0];
            $productCode = $row[2]; //商品代码
            $productCodes[] = $productCode;
            $phone = $row[17];
            $temp[$phone][] = [
                'row' => $key,
                'order_no' => $orderNo,
                'productCode' => $productCode,
                'quantity' => $row[9],  //数量
                'order_time' => $row[18],   //下单时间
                'pay_time' => $row[18],   //付款时间
                'remarks' => $row[19],    //备注
                'total_money' => $row[11],  //总金额
                'total_pay' => $row[11],  //实付总额
                'addressee_name' => $row[12], //收件人姓名
                'addressee_phone' => $phone, //收件人手机
                'address' => $row[13] . $row[14] . $row[15], //地址
                'price' => $row[10]
            ];
        }

        //查询商品信息
        $results = DB::table('products as p')
            ->join('product_order_source as pos', 'product', '=', 'p.id')
            ->where('pos.order_source',$this->sourceId)
            ->whereIn('p.code', $productCodes)
            ->select(DB::raw('p.code,pos.source_name,pos.source_code,pos.source_quantity'))
            ->get();

        $productsInfo = [];
        //整理商品信息数据,key为{商品code}_{商品数量}
        foreach ($results as $row) {
            $productsInfo[$row->code.'_'.$row->source_quantity] = $row;
        }

        foreach ($temp as $tempOrderNo => &$orders) {
            if (count($orders) == 1 ) {
                $color = '';
            } else {
                $color = $this->getColor();
            }
            foreach ($orders as $i=>&$order) {
                $order['color'] = $color;
                //查询商品名称等信息是否在results中
                $index = $order['productCode'].'_'.$order['quantity'];
                if (empty($productsInfo[$index])) {
                    $this->addError($order['row']+1,"找不到该来源中相对应的商品信息，请检查{$order['productCode']}是否添加了相应的来源信息");
//                    $this->errorData[] = $order;
                    unset($orders[$i]);
                } else {
                    $order['source_name'] = $productsInfo[$index]->source_name;
                    $order['source_code'] = $productsInfo[$index]->source_code;
                    $this->targetData[] = $order;
                }
            }
            if (empty($orders)) {
                unset($temp[$tempOrderNo]);
            }
        }
    }

    protected function toExcel()
    {
        $colors = [];
        $exportData = [];
        $exportData[] = $this->targetTitle;
        //获取颜色
        foreach ($this->targetData as $key=>$row) {
            if (!empty($row['color'])) {
                $colors[$row['color']][] = $key+2;
            }
            $exportData[] = [
                $row['order_no'],   //订单
                $row['order_time'],  //下单时间
                $row['order_time'], //付款时间
                '',  //交易类型
                $row['remarks'],  //备注
                '',  //买家留言
                $row['total_money'],  //总金额
                '',   //运费
                $row['total_pay'],  //实付总额
                $row['addressee_name'],  //收货人姓名
                $row['addressee_phone'],  //手机
                '',  //固话
                $row['address'], //地址
                '',  //邮编
                '',  //电子邮箱
                $row['source_code'],  //商品编码
                $row['source_name'],  //商品名称
                '',  //规格名称
                $row['quantity'],  //数量
                $row['price'],  //单价
                $row['total_pay'],  //实付
            ];
        }
        $writer = new \XLSXWriter();
        $writer->writeSheet($exportData);
        $writer->writeToFile($this->targetPath);
        $writer->__destruct();

        $workbook = IOFactory::load($this->targetPath);
        $sheet = $workbook->getActiveSheet();
        foreach ($colors as $color => $rows) {
            $startRow = 0;
            $endRow = 0;
            for ($i=0;$i<count($rows);$i++) {
                if ($i+1<count($rows) && $rows[$i] == $rows[$i+1]) {
                    if ($startRow == 0) {
                        $startRow = $rows[$i];
                    }
                    $endRow = $rows[$i+1];
                } else {
                    if ($startRow == 0 && $endRow == 0) {
                        $startRow = $endRow = $rows[$i];
                    }
                    $sheet->getStyle("A{$startRow}:U{$endRow}")->getFill()
                          ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                        ->getStartColor()->setARGB('FF'.$color);
                    $startRow = 0;
                    $endRow = 0;
                }
            }
        }
        //调整宽度
        for ($j=1;$j<=21;$j++) {
            if (in_array($j,[1,2,3,13,17])) {
                $width = 55;
            } else {
                $width = 15;
            }
            $sheet->getColumnDimensionByColumn($j)->setWidth($width);

        }
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($workbook);
        $writer->save($this->targetPath);
    }
}